<?php
defined('SYSPATH') or die('No direct script access.') ;
/**
 * @author Y.N
 *  2011/5/9
 */
class Cli_Clean extends CLI
{

	protected static $_path = Null;

	public function main()
	{

		self::update_goods_stock();

		/*
		$page = $this->args->page ? (int) $this->args->page : 0;

		switch ($page)
		{
		    case 1:
				self::fix_product_data_two();
				break;
			case 2:
				self::fix_product_data_three();
				break;
			default :
				self::fix_product_data_one();
		}

		/*
		$shop_id = $this->args->shop_id ? (int) $this->args->shop_id : '0';
		if ( ! empty($shop_id))
		{
			self::deleted_goods_description($shop_id);
		}
		*/
	}



	/**
	 * 更新商品库存
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/12/28
	 */
	public static function update_goods_stock()
	{
		$select = DB::select('goods_id', 'shop_id')
			->from('goods')
			->where('deleted', '=', 0)
			->where('product_id', '>', 0);
		$iterator = new Db_Iterator($select, 'default', 1000);
		while ($iterator->valid())
		{
			foreach ($iterator->current() as $g)
			{
				$cert_type = DB::select('cert_type')
					->from('shops')
					->where('shop_id', '=', $g['shop_id'])
					->fetch_one();
				if ( ! $cert_type)
				{
					continue;
				}
				$skus = Detail::get_item_skus($g['goods_id']);
				if ( ! empty($skus))
				{
					$stock_sum = 0;
					foreach ($skus as $sku)
					{
						$set = array(
							'stock' => 100,
						);
						DB::update('item_skus')
							->set($set)
							->where('sku_id', '=', $sku['sku_id'])
							->execute();
						$stock_sum += 100;
					}
					$update = array(
						'stock' => $stock_sum,
					);
					DB::update('goods')
						->set($update)
						->where('goods_id', '=', $g['goods_id'])
						->execute();
					CLI::output(">");
				}
				unset($g);
			}
			$iterator->next();
		}

		CLI::output("\n商品库存同步完毕...");
	}

	/**
	 * 清理商品描述外部链接
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/10/31
	 */
	public static function clean_description()
	{
		$goods = DB::select('goods_id', 'description')
			->from('goods_fields')
			->where('goods_id', '<', 100000)
			->fetch_all();
		foreach ($goods as $g)
		{
			$description = Items::clearurl($g['description']);
			DB::update('goods_fields')
				->set(array('description' => $description))
				->where('goods_id', '=', $g['goods_id'])
				->execute();
		}

	}

	/**
	 * 清理重复spu数据
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/26
	 */
	public static function clean_products()
	{

		$ids = DB::select('product_id')
			->from('products')
			->where('is_new', '=', 2)
			->fetch_all();
		$count_num = 0;
		foreach ($ids as $p)
		{
			$count = DB::select(DB::expr('count(*)'))
				->from('goods')
				->where('product_id', '=', $p['product_id'])
				->fetch_one();
			if ( ! $count)
			{
				$count_num += 1;
				DB::delete('products')
					->where('product_id', '=', $p['product_id'])
					->execute();
				DB::delete('product_imgs')
					->where('product_id', '=', $p['product_id'])
					->execute();
			}
		}
		CLI::output("\n重复产品(".$count_num.")数据删除完毕...");
	}


	/**
	 * 修正SPU数据
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/10/19
	 */
	public static function fix_product_data_one()
	{
		$file = TMPPATH.'/logs/cli/goods.log';

		$goods = DB::select('goods_id', 'props', 'cid', 'product_id', 'goods_title')
			->from('goods')
			->where('product_id', '=', 0)
			->where('deleted', '=', 0)
			->where('props', '<>', '')
			->order_by('goods_id', 'desc')
			->fetch_all();
		foreach ($goods as $g)
		{
			$product_id = 0;
			$props = explode(';', $g['props']);
			$binds = array();
			$brands = array();
			foreach ($props as $p)
			{
				$explode = explode(':', $p);
				$pid = current($explode);

				// 是否非关键属性
				$is_fit = DB::select('is_key_prop')
					->from('item_props_view')
					->where('is_price_prop', '=', 0)
					->where('is_color_prop', '=', 0)
					->where('pid', '=', $pid)
					->where('cid', '=', $g['cid'])
					->fetch_one();
				if ( ! $is_fit)
				{
					$binds[] = $p;
				} else {
				    $brands[] = $p;
				}
			}

			$go = true;

			$brands_old = $brands;
			foreach ($brands as $k => $b)
			{
				$explode = explode(':', $b);
				$pid = current($explode);
				$vid = next($explode);
				$p_count = DB::select(DB::expr('count(*)'))
					->from('item_props_view')
					->where('is_key_prop', '=', 1)
					->where('pid', '=', $pid)
					->where('cid', '=', $g['cid'])
					->where('parent_pid', '=', 0)
					->fetch_one();
				$name_alias = DB::select('name_alias')
					->from('item_values_view')
					->where('pid', '=', $pid)
					->where('cid', '=', $g['cid'])
					->where('vid', '=', $vid)
					->fetch_one();
				if ($p_count)
				{
					unset($brands[$k]);
					array_unshift($brands, $b);
				} else {
				    unset($brands_old[$k]);
					array_unshift($brands_old, $b);
				}
				if (stristr($name_alias, '其他') OR stristr($name_alias, '其它'))
				{
					$go = false;
				}
			}
			$brand_data = implode(';', $brands);
			$brands_old_data = implode(';', $brands_old);

			if (count($brands)>1)
			{
				$product_id = (int) DB::select('product_id')
					->from('products')
					->where_open()
					->where('props', '=', $brand_data)
					->or_where('props', '=', $brands_old_data)
					->where_close()
					->where('cid', '=', $g['cid'])
					->where('status', '=', 3)
					->where('is_new', '<>', 2)
					->fetch_one();
			}
			if ( ! $product_id AND $go AND count($brands)>1)
			{
				$product_id = (int) DB::select('product_id')
					->from('products')
					->where_open()
					->where('props', '=', $brand_data)
					->or_where('props', '=', $brands_old_data)
					->where_close()
					->where('cid', '=', $g['cid'])
					->where('status', '=', 3)
					->where('is_new', '=', 2)
					->order_by('product_id', 'asc')
					->fetch_one();
			}

			/*
			if ( ! $product_id AND ! empty($binds) AND count($binds)>2)
			{
				$binds = implode(';', $binds);
				$product_id = (int) DB::select('product_id')
					->from('products')
					->where_open()
					->where('binds', 'REGEXP', '^'.$binds)
					->or_where('product_name', '=', trim($g['goods_title']))
					->where_close()
					->where('cid', '=', $g['cid'])
					->where('status', '=', 3)
					->where('is_new', '=', 2)
					->order_by('product_id', 'asc')
					->fetch_one();
			}
			*/
			if ($product_id AND $product_id != $g['product_id'])
			{
				DB::update('goods')
					->set(array('product_id' => $product_id))
					->where('goods_id', '=', $g['goods_id'])
					->execute();

				if ( ! file_exists($file))
				{
					file_put_contents($file, '');
				}
				file_put_contents($file, "商品ID".$g['goods_id']."更新成功\r\n", FILE_APPEND);
				CLI::output("\n商品ID".$g['goods_id']."更新成功\n");
			}
			CLI::output(">");

		}
		CLI::output("\n商品更新完毕\n");
	}

	/**
	 * 修正SPU数据
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/10/19
	 */
	public static function fix_product_data_two()
	{
		$file = TMPPATH.'/logs/cli/goods.log';

		$goods = DB::select('goods_id', 'props', 'cid')
			->from('goods')
			->where('product_id', '=', 0)
			->where('deleted', '=', 0)
			->where('props', '<>', '')
			->fetch_all();
		foreach ($goods as $g)
		{
			$props = explode(';', $g['props']);
			$binds = array();
			$brands = array();
			foreach ($props as $p)
			{
				$explode = explode(':', $p);
				$pid = current($explode);

				// 是否非关键属性
				$is_fit = DB::select('is_key_prop')
					->from('item_props_view')
					->where('is_price_prop', '=', 0)
					->where('is_color_prop', '=', 0)
					->where('pid', '=', $pid)
					->where('cid', '=', $g['cid'])
					->fetch_one();
				if ( ! $is_fit)
				{
					$binds[] = $p;
				} else {
				    $brands[] = $p;
				}
			}

			if (count($brands)>1)
			{
				$brands = implode(';', $brands);
				$product_id = DB::select('product_id')
					->from('products')
					->where('props', '=', $brands)
					->where('is_new', '<>', 2)
					->where('cid', '=', $g['cid'])
					->fetch_one();
			} elseif ( ! empty($binds) AND count($binds)>3) {
				$binds = implode(';', $binds);
				$product_id = DB::select('product_id')
					->from('products')
					->where('binds', 'REGEXP', '^'.$binds)
					->where('is_new', '=', 2)
					->where('cid', '=', $g['cid'])
					->fetch_one();
			}
			if ( ! empty($product_id))
			{
				DB::update('goods')
					->set(array('product_id' => $product_id))
					->where('goods_id', '=', $g['goods_id'])
					->execute();
				if ( ! file_exists($file))
				{
					file_put_contents($file, '');
				}
				file_put_contents($file, "商品ID".$g['goods_id']."更新成功\r\n", FILE_APPEND);
				CLI::output("\n商品ID".$g['goods_id']."更新成功\n");
			}
			CLI::output(">");
		}
		CLI::output("\n商品更新完毕\n");
	}

	/**
	 * 修正属性为空数据
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/10/24
	 */
	public static function fix_product_data_three()
	{
		$products = DB::select('product_id', 'props', 'binds', 'cid')
			->from('products')
			->where('is_new', '=', 2)
			->where('status', '=', 3)
			->where('props', 'REGEXP', '^[0-9]+:[0-9]+$')
			->fetch_all();

		foreach ($products as $p)
		{

				$update = array(
					'props' => '',
					'props_str' => '',
				);
				DB::update('products')
					->set($update)
					->where('product_id', '=', $p['product_id'])
					->execute();
				CLI::output('产品ID：'.$p['product_id']."更新完毕\n");
		}
		CLI::output('SPU更新完毕');
	}

	/**
	 * 收货地址修正
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/9/9
	 */
	public static function address_fixed()
	{
		$address = DB::select('address_id', 'city', 'district')
			->from('addresses')
			->where('province', '<>', '')
			->fetch_all();
		foreach ($address as $k => $adds)
		{
			if ( ! empty($adds['district']))
			{
				$region_id = DB::select('region_id')
					->from('regions')
					->where('region_name', '=', $adds['district'])
					->fetch_one();
			} else {
			    if ( ! empty($adds['city']))
			    {
					$region_id = DB::select('region_id')
						->from('regions')
						->where('region_name', '=', $adds['city'])
						->fetch_one();
			    }
			}
			if ( ! empty($region_id))
			{
				$set = array(
					'bottom_region_id' => $region_id,
				);
				DB::update('addresses')
					->set($set)
					->where('address_id', '=', $adds['address_id'])
					->execute();
			}
			CLI::output(">");
		}
		CLI::output("\n收货地址修正完毕\n");
	}

	/**
	 * SPU统计
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/9/9
	 */
	public static function stats_spu()
	{
		self::$_path = RESPATH.'etao/';

		// 抓取SPU
		$return = array();

		$goods = DB::select('g.goods_id', 'g.product_id', 's.protections', 'g.shop_id')
			->from(array('goods', 'g'))
			->join(array('shops', 's'))
			->on('g.shop_id', '=', 's.shop_id')
			->where('g.product_id', '!=', 0)
			->where('g.deleted', '=', 0)
			->where('s.status', '=', 4)
			->where('s.deleted', '=', 0)
			->fetch_all();

		foreach ($goods as $g)
		{
			$products = DB::select('cat_name', 'product_name')
				->from('products')
				->where('product_id', '=', $g['product_id'])
				->fetch_row();

			$return[$g['product_id']]['products'] = $products;

			// 写入商品数量
			$return[$g['product_id']]['goods'][] = $g['goods_id'];

			// 统计商家数量
			$return[$g['product_id']]['shops'][$g['shop_id']] = $g['shop_id'];

			if ( ! empty($g['protections']))
			{
				// 写入消保数量
				$return[$g['product_id']]['is_protections'][] = $g['goods_id'];
			} else {
				// 写入非消保数量
				$return[$g['product_id']]['no_protections'][] = $g['goods_id'];
			}
		}
		$data = array();
		$content = "spuID,spu类目,spu名称,商家数,有消保,木有消保\r\n";
		foreach ($return as $k => $value)
		{
			$data['product_id'] = $k;
			$data['cat_name'] = $value['products']['cat_name'];
			$data['product_name'] = $value['products']['product_name'];
			$data['shops'] =  ! empty($value['shops']) ? count($value['shops']) : 0;
			$data['is_protections'] =  ! empty($value['is_protections']) ? count($value['is_protections']) : 0;
			$data['no_protections'] = ! empty($value['no_protections']) ? count($value['no_protections']) : 0;
			$content .= implode("," ,$data)."\r\n";
		}
		$content = mb_convert_encoding($content,"gbk","utf-8");
		$file = self::$_path.'spu.csv';
		file_put_contents($file, $content);
		CLI::output("\n统计完毕\n");
	}


	/**
	 * 抓取最新数据至扩展表
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/9/13
	 */
	public static function catch_goods_description()
	{
		// 抓取最新商品数据至扩展表
		$goods = DB::select('goods_id', 'description')
			->from('goods_fields')
			->where('goods_id', '>', 210000)
			->fetch_all();
		foreach ($goods as $g)
		{
			$count = DB::select(DB::expr('count(*)'))
				->from('goods_fields')
				->where('goods_id', '=', $g['goods_id'])
				->fetch_one();
			if ( ! $count)
			{
				$set = array(
					'goods_id' => $g['goods_id'],
					'description' => $g['description'],
				);
				DB::replace('goods_fields', $set)->execute();
			}
		}
		CLI::output("\n扩展信息抓取完毕\n");
	}


	// 描述抓取

	/**
	 * Short description.
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/9/20
	 */
	public static function deleted_goods_description($shop_id)
	{
		$goods = DB::select('goods_id')
			->from('goods')
			->where('shop_id', '=', $shop_id)
			->fetch_all();

		foreach ($goods as $k => $v)
		{
			DB::delete('goods')
				->where('goods_id', '=', $v['goods_id'])
				->execute();
			DB::delete('goods_props')
				->where('goods_id', '=', $v['goods_id'])
				->execute();
			DB::delete('goods_images')
				->where('goods_id', '=', $v['goods_id'])
				->execute();
		}
		CLI::output("\n商品信息删除完毕\n");
	}
}